<!-- 设备管理-设备列表页面 -->
<template>
  <div class="app-container">
    <px-tabs
      v-if="!equipopen && !equipopenDetail"
      v-model="activeName"
      style="margin-top: -10px; margin-left: 10px; background: none"
      @tab-change="handleTabChange"
    >
      <px-tab-pane name="fixed">
        <template #label>
          <p class="pane-bottom">固定取样</p>
          <p class="pane-line" />
        </template>
      </px-tab-pane>
      <px-tab-pane name="nonFixed">
        <template #label>
          <p class="pane-bottom">非固定取样</p>
          <p class="pane-line" /> </template
      ></px-tab-pane>
    </px-tabs>
    <px-form v-show="showSearch" ref="queryRef" class="custom-form-ui" :model="queryParams" :inline="true" label-width="90px">
      <px-form-item label="取样点">
        <px-select v-model="queryParams.samplingLocationCode" placeholder="请选择取样点" clearable style="width: 240px" filterable>
          <px-option v-for="dict in liquidList" :key="dict.id" :label="dict.itemName" :value="dict.itemCode" />
        </px-select>
      </px-form-item>
      <px-form-item label="取样日期" style="width: 516px !important">
        <px-date-picker
          v-model="dateRange"
          type="datetimerange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          :default-time="defaultTime"
        />
      </px-form-item>
      <px-button style="margin-top: -17px" type="primary" icon="" @click="handleQuery('search')">搜索</px-button>
      <px-button style="margin-top: -17px" icon="" @click="resetQuery">重置</px-button>
    </px-form>
    <uploadFiles v-if="dialogVisible" v-model="dialogVisible" @submit="submitHandler" />
    <px-row :gutter="10" class="mb8">
      <px-col :span="1.5">
        <px-button v-has="'PURE_WATER_TESTING_ADD'" type="primary" icon="" @click="handleAdd">新增</px-button>
      </px-col>
      <!-- <px-col :span="1.5">
        <px-upload :file-list="fileList" action="#" :http-request="batchImport" accept=".xlsx" :show-file-list="false">
          <px-button type="primary" plain>批量导入</px-button>
        </px-upload>
      </px-col> -->
      <px-col :span="1.5">
        <px-button v-has="'PURE_WATER_TESTING_EXPORT'" type="primary" plain icon="" @click="handleExport">导出</px-button>
      </px-col>
      <!-- <px-col :span="1.5">
        <px-button type="primary" plain icon="" @click="handleExport2">下载模板</px-button>
      </px-col> -->
      <!-- <px-col :span="1.5">
        <px-button v-has="'CommonEquipListDelete'" type="danger" plain icon="" :disabled="multiple" @click="handleDelete">删除</px-button>
      </px-col> -->
    </px-row>

    <px-table
      v-if="!equipopen && !equipopenDetail"
      v-loading="loading"
      :data="typeList"
      height="calc(100vh - 350px)"
      show-overflow-tooltip
      border
      @selection-change="handleSelectionChange"
    >
      <!-- <px-table-column type="selection" width="40" /> -->
      <px-table-column label="序号" width="60" align="center" fixed="left">
        <template #default="{ $index }">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
        </template>
      </px-table-column>
      <!-- <px-table-column label="取样日期" width="200" prop="samplingDate">
        <template #default="scope">
          <span>{{ scope.row.samplingDate ? scope.row.samplingDate : "-" }}</span>
        </template>
      </px-table-column> -->

      <px-table-column label="取样时间" prop="samplingTime">
        <template #default="scope">
          <span>{{ scope.row.samplingDate ? scope.row.samplingDate : "-" }}</span
          >&nbsp;
          <span>{{ scope.row.samplingTime ? scope.row.samplingTime : "-" }}</span>
        </template>
      </px-table-column>

      <px-table-column label="取样点" prop="samplingLocation">
        <template #default="scope">
          <span v-if="activeName === 'fixed'">{{ scope.row.samplingLocation ? scope.row.samplingLocation : "-" }}</span>
          <span v-else>{{ scope.row.samplingLocationName ? scope.row.samplingLocationName : "-" }}</span>
        </template>
      </px-table-column>
      <px-table-column label="取样人" prop="samplingOperator">
        <template #default="scope">
          <span>{{ scope.row.samplingOperator ? scope.row.samplingOperator : "-" }}</span>
        </template>
      </px-table-column>
      <px-table-column label="检测指标" width="140" prop="detectExceptionResultCount">
        <template #default="scope">
          <span>{{ scope.row.detectExceptionResultCount > 0 ? scope.row.detectExceptionResultCount + "项异常" : "无异常" }}</span>
        </template>
      </px-table-column>
      <px-table-column label="检测结果" width="140" prop="testConclusion" />
      <px-table-column v-if="activeName === 'fixed'" label="复检结果" width="140" prop="recheckConclusion" />
      <!-- <px-table-column
        v-for="(item, index) in tableColumns"
        :key="item.key"
        :props="item.itemName"
        :label="`${item.itemName}${item.controlValue}`"
        width="140"
      >
        <template #default="scope">
          <span :style="{ color: scope.row.testResult[index].ooc ? '#ef4444' : '' }">{{
            scope.row.testResult[index].testValue ? scope.row.testResult[index].testValue : "-"
          }}</span>
        </template>
      </px-table-column> -->
      <px-table-column fixed="right" label="操作" align="center" width="180">
        <template #default="scope">
          <px-button v-if="activeName === 'fixed' && scope.row.testConclusion === '不通过'" link type="primary" @click="handleReview(scope.row)">
            <px-tooltip class="box-item" content="复核" placement="top">
              <px-icon>
                <Approval />
              </px-icon> </px-tooltip
          ></px-button>
          <px-button v-has="'PURE_WATER_TESTING_DETAIL'" link type="primary" @click="handleDetail(scope.row.id)">
            <px-tooltip class="box-item" content="分析" placement="top">
              <px-icon>
                <Tickets />
              </px-icon> </px-tooltip
          ></px-button>
          <px-button v-if="scope.row.status != 'INVALID'" v-has="'PURE_WATER_TESTING_EDITOR'" link type="primary" @click="handleEditor(scope.row.id)">
            <px-tooltip class="box-item" content="编辑" placement="top">
              <px-icon>
                <EditPen />
              </px-icon> </px-tooltip
          ></px-button>
          <px-button v-if="scope.row.status != 'INVALID'" v-has="'PURE_WATER_TESTING_DELETE'" link type="danger" @click="handleDelete(scope.row)"
            ><px-tooltip class="box-item" content="删除" placement="top">
              <px-icon>
                <Delete />
              </px-icon> </px-tooltip
          ></px-button>
        </template>
      </px-table-column>
      <template #empty>
        <px-empty :image-size="150" />
      </template>
    </px-table>

    <pagination
      v-if="!equipopen && !equipopenDetail"
      v-show="total > 0"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      style="margin-bottom: -10px"
      :total="total"
      @pagination="getList"
    />
    <px-dialog v-model="reviewDialogVisible" title="关联复查记录" width="60%" :before-close="handleClose" draggable>
      <el-form v-show="!isReviewResult" ref="queryRef" class="custom-form-ui" :model="queryParams" :inline="true" label-width="90px">
        <px-form-item label="取样日期" style="width: 516px !important">
          <px-date-picker
            v-model="reviewDateRange"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="changeReviewDateRange"
          />
        </px-form-item>
      </el-form>

      <px-table v-loading="loading" :data="reviewList" show-overflow-tip border height="500">
        <px-table-column v-if="!isReviewResult" width="50">
          <template #default="{ row }">
            <px-radio v-model="selectedRowId" :label="row.id">
              {{ " " }}
              <!-- 空字符串保持单元格内容为空，只显示单选框 -->
            </px-radio>
          </template>
        </px-table-column>
        <px-table-column label="取样点" prop="samplingLocation">
          <template #default="scope">
            <span>{{ scope.row.samplingLocation ? scope.row.samplingLocation : "-" }}</span>
          </template>
        </px-table-column>
        <px-table-column label="取样时间" prop="samplingTime" width="180">
          <template #default="scope">
            <span>{{ scope.row.samplingDate }}</span
            >&nbsp;
            <span>{{ scope.row.samplingTime }}</span>
          </template>
        </px-table-column>
        <px-table-column label="取样人" prop="samplingOperator" />
        <px-table-column label="检测指标" prop="detectExceptionResultCount">
          <template #default="scope">
            <span>{{ scope.row.detectExceptionResultCount > 0 ? scope.row.detectExceptionResultCount + "项异常" : "无异常" }}</span>
          </template>
        </px-table-column>
        <px-table-column v-if="isReviewResult" label="检测结果" prop="testConclusion" />
      </px-table>
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="reviewDialogVisible = false">取消</px-button>
          <px-button v-if="isReviewResult" type="primary" @click="reAssocite"> 重新关联 </px-button>
          <px-button v-else :disabled="!selectedRowId" type="primary" @click="associate"> 关联 </px-button>
        </span>
      </template>
    </px-dialog>
    <!-- 添加或修改参数配置对话框 -->

    <px-scrollbar v-if="equipopen" class="editorEquip">
      <px-button style="margin-left: 24px" type="primary" :icon="ArrowLeft" @click="cancel">返回</px-button>
      <div class="px-descriptions__title" style="margin: 20px 0 0 20px">基本信息</div>
      <px-row style="padding: 20px 20px 0">
        <px-col :span="8">
          <px-descriptions class="margin-top" :column="1" border>
            <px-descriptions-item>
              <template #label>
                <div class="cell-item">记录编号:</div>
              </template>
              {{ equipdata.documentNumber }}
            </px-descriptions-item>
            <!-- <px-descriptions-item>
              <template #label>
                <div class="cell-item">取样点:</div>
              </template>
              {{ equipdata.samplingLocation }}
            </px-descriptions-item> -->
          </px-descriptions>
        </px-col>
        <px-col :span="8">
          <px-descriptions class="center2" :column="1" border>
            <px-descriptions-item>
              <template #label>
                <div class="cell-item">认证报告编号:</div>
              </template>
              {{ equipdata.reportNumber }}
            </px-descriptions-item>
          </px-descriptions>
        </px-col>
        <!-- <px-col :span="8">
          <px-descriptions class="center2" :column="1" border style="border-bottom: none">
            <px-descriptions-item>
              <template #label>
                <div class="cell-item">取样人:</div>
              </template>
              {{ equipdata.samplingOperator }}
            </px-descriptions-item>
          </px-descriptions>
        </px-col> -->
        <px-col :span="8">
          <px-descriptions class="center2" :column="1" border>
            <px-descriptions-item>
              <template #label>
                <div class="cell-item">取样时间:</div>
              </template>
              {{ equipdata.samplingTime }}
            </px-descriptions-item>
            <!-- <px-descriptions-item>
              <template #label>
                <div class="cell-item">负责人:</div>
              </template>
              {{ equipdata.responsiblePerson }}
            </px-descriptions-item> -->
          </px-descriptions>
        </px-col>
      </px-row>
      <px-row style="padding: 0 20px">
        <px-col :span="8">
          <px-descriptions class="center3" :column="1" border>
            <px-descriptions-item>
              <template #label>
                <div class="cell-item">取样点:</div>
              </template>
              {{ activeName === "fixed" ? equipdata.samplingLocation : equipdata.samplingLocationName }}
            </px-descriptions-item>
          </px-descriptions>
        </px-col>
        <px-col :span="8">
          <px-descriptions class="center3 center2" :column="1" border>
            <px-descriptions-item>
              <template #label>
                <div class="cell-item">负责人:</div>
              </template>
              {{ equipdata.responsiblePerson }}
            </px-descriptions-item>
          </px-descriptions>
        </px-col>
        <px-col :span="8">
          <px-descriptions class="center3" :column="1" border>
            <px-descriptions-item>
              <template #label>
                <div class="cell-item">检测机构:</div>
              </template>
              {{ testManufacturerList.find(item => item.code === equipdata.testManufacturer)?.name }}
            </px-descriptions-item>
          </px-descriptions>
        </px-col>
      </px-row>
      <px-row style="padding: 0 20px">
        <px-col :span="8">
          <px-descriptions class="center3" :column="1" border>
            <px-descriptions-item>
              <template #label>
                <div class="cell-item">检测结果:</div>
              </template>
              {{ equipdata.testConclusion }}
            </px-descriptions-item>
          </px-descriptions>
        </px-col>
      </px-row>
      <div style="width: 100%; padding: 0 20px 20px; clear: both">
        <div class="px-descriptions__title" style="padding: 20px 0">检测项目</div>
        <px-scrollbar>
          <div v-if="activeName === 'fixed'">
            <div class="detailTableTop">
              <div class="detailTopList">检测项目</div>
              <div v-for="item in equipdata.testItems" :key="item.key" class="detailTopList">{{ item.itemName }}</div>
            </div>
            <div class="detailTableMain">
              <div class="detailTopList">Control limit</div>
              <div v-for="item in equipdata.testItems" :key="item.key" class="detailTopList">{{ item.controlValue }}</div>
            </div>
            <div class="detailTableMain">
              <div class="detailTopList">检测结果</div>
              <div v-for="item in equipdata.testResult" :key="item.key" class="detailTopList">
                {{ item.value }}
              </div>
            </div>
            <div class="detailTableMain">
              <div class="detailTopList">质量分析</div>
              <div v-for="(item, key) in equipdata.testItems" :key="key" class="detailTopList" @click="selectSpcHandler(item)">
                <div class="detailSpc" :style="{ backgroundColor: spcCurrentKey.key == item.key ? '#1ED794' : '#dcdcdc' }">SPC分析</div>
              </div>
            </div>
          </div>
          <div v-else style="display: flex; width: 100%">
            <div class="tableTop">
              <div class="topList" style="background-color: #e7eefb">检测项目</div>
              <div v-for="item in equipdata.testItems" :key="item.key" class="topList">{{ item.key }}</div>
            </div>
            <div class="tableMain">
              <div class="topList" style="background-color: #e7eefb">单位</div>
              <div v-for="item in equipdata.testItems" :key="item.key" class="topList">
                <span> {{ item.itemUnit }}</span>
              </div>
            </div>
            <div class="tableMain">
              <div class="topList" style="background-color: #e7eefb">Control limit</div>
              <div v-for="item in equipdata.testItems" :key="item.key" class="topList">
                <span>{{ item.controlValue }}</span>
              </div>
            </div>
            <div class="tableMain">
              <div class="topList" style="background-color: #e7eefb; border-right: 1px solid #dfdfdf">检测结果</div>
              <div
                v-for="item in equipdata.testResult"
                :key="item.key"
                class="topList testResult"
                style="padding: 3px; border-right: 1px solid #dfdfdf"
              >
                <span>{{ item.value }}</span>
              </div>
            </div>
          </div>
        </px-scrollbar>
      </div>
      <div v-if="activeName === 'fixed'" style="width: 100%; padding: 0 20px 20px; clear: both">
        <spcCharts :spcCurrentKey="spcCurrentKey" />
      </div>
      <div style="width: 100%; padding: 0 0 0 20px; clear: both">
        <div class="px-descriptions__title" style="padding: 20px 0">取样照片</div>
        <PhotoUpload photoType="view" :photoData="{ moduleName: 'GENERAL_CHEMICALS' }" :photoList="equipdata.samplingPhoto" />
      </div>
      <div style="width: 100%; padding: 0 20px 20px; clear: both">
        <div class="px-descriptions__title" style="padding: 20px 0">附件</div>
        <FileUpload fileType="view" :fileData="{ moduleName: 'GENERAL_CHEMICALS' }" :fileList="equipdata.attachmentFile" />
      </div>
    </px-scrollbar>
    <px-scrollbar v-if="equipopenDetail" class="addEquip">
      <px-button style="margin-left: 24px" type="primary" :icon="ArrowLeft" @click="equipopenDetailcancel">返回</px-button>
      <px-form
        ref="detailruleFormRef"
        :disabled="fromdisable"
        :rules="rules"
        :model="equipdata"
        :inline="true"
        class="demo-form-inline"
        label-width="160px"
      >
        <div
          class="box-card1"
          :style="{
            height: jibenxinxiFlg == true ? '' : '42px'
          }"
        >
          <div class="card-header" @click="setqingdanFlg()">
            <div class="card-title">基本信息</div>
            <div class="card-main">
              <px-icon v-if="!jibenxinxiFlg">
                <ArrowDown />
              </px-icon>
              <px-icon v-else>
                <ArrowUp />
              </px-icon>
            </div>
          </div>
          <div class="form-div">
            <px-row>
              <px-col :span="8">
                <px-form-item label="记录编号">
                  <px-input v-model="equipdata.documentNumber" disabled="true" placeholder="记录编号为系统生成" clearable /> </px-form-item
              ></px-col>
              <px-col :span="8">
                <px-form-item label="认证报告编号">
                  <px-input v-model="equipdata.reportNumber" placeholder="请输入认证报告编号" clearable /> </px-form-item
              ></px-col>
              <px-col :span="8">
                <px-form-item label="检测机构">
                  <px-select v-model="equipdata.testManufacturer" placeholder="请选择检测机构" style="width: calc(100% - 100px)">
                    <px-option v-for="(item, index) in testManufacturerList" :key="index" :label="item.name" :value="item.code" />
                  </px-select>
                </px-form-item>
              </px-col>
              <!-- <px-col :span="8">
                <px-form-item label="排水时段" style="width: calc(100% - 100px)" prop="useDateFrom">
                  <px-time-picker
                    v-model="equipdata.useDateFrom"
                    is-range
                    range-separator="-"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    format="HH:mm:ss"
                    value-format="HH:mm:ss"
                    @change="checkdrain"
                  />
                </px-form-item>
              </px-col> -->
            </px-row>
            <px-row>
              <px-col :span="8">
                <px-form-item v-if="activeName === 'fixed'" label="取样点" prop="samplingLocationCode">
                  <px-select
                    v-model="equipdata.samplingLocationCode"
                    placeholder="请选择取样点"
                    style="width: calc(100% - 100px)"
                    clearable
                    filterable
                    @change="checklocation"
                  >
                    <px-option v-for="dict in liquidList" :key="dict.id" :label="dict.itemName" :value="dict.itemCode" />
                  </px-select>
                </px-form-item>
                <px-form-item v-else label="取样点" prop="samplingLocationCode">
                  <px-input v-model="equipdata.samplingLocationCode" placeholder="请输入取样点" style="width: calc(100% - 100px)" clearable />
                </px-form-item>
              </px-col>
              <!-- <px-col :span="8">
                <px-form-item label="排水量(m³)" prop="drainageVolume">
                  <px-input v-model="equipdata.drainageVolume" placeholder="请输入排水量(m³)" clearable />
                </px-form-item>
              </px-col> -->
              <px-col :span="8">
                <px-form-item label="取样人" prop="samplingOperatorId">
                  <px-select
                    v-model="equipdata.samplingOperatorId"
                    placeholder="请选择"
                    style="width: calc(100% - 100px)"
                    clearable
                    filterable
                    @change="changesamplingOperator"
                  >
                    <px-option v-for="item in userList" :key="item.value" :label="item.label" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="负责人" prop="responsiblePersonId">
                  <px-select
                    v-model="equipdata.responsiblePersonId"
                    placeholder="请选择"
                    style="width: calc(100% - 100px)"
                    clearable
                    filterable
                    @change="changeresponsiblePerson"
                  >
                    <px-option v-for="item in userList" :key="item.value" :label="item.label" :value="item.value" />
                  </px-select> </px-form-item
              ></px-col>
            </px-row>
            <px-row>
              <px-col :span="8">
                <px-form-item label="取样时间" prop="samplingTime">
                  <px-date-picker
                    v-model="equipdata.samplingTime"
                    style="width: calc(100% - 100px)"
                    placeholder="请选择取样时间"
                    type="datetime"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="检测结果" prop="testConclusion">
                  <px-select v-model="equipdata.testConclusion" placeholder="请选择" style="width: calc(100% - 100px)" clearable filterable>
                    <px-option label="通过" value="通过" />
                    <px-option label="不通过" value="不通过" />
                  </px-select>
                </px-form-item>
              </px-col>
            </px-row>
          </div>
        </div>
        <div
          class="box-card2"
          :style="{
            height: moxingshezhiFlg == true ? '' : '42px'
          }"
        >
          <div class="card-header" @click="setmoxingshezhiFlg()">
            <div class="card-title">检测项目</div>
            <div class="card-main">
              <px-icon v-if="!moxingshezhiFlg">
                <ArrowDown />
              </px-icon>
              <px-icon v-else>
                <ArrowUp />
              </px-icon>
            </div>
            <div>
              <px-button
                v-has="'PURE_WATER_TESTING_IMPORT'"
                style="position: relative; bottom: 9px"
                type="primary"
                plain
                icon=""
                @click.stop="handleImport"
                >导入</px-button
              >
            </div>
          </div>
          <px-scrollbar class="form-div">
            <div class="info-form-content">
              <div v-if="buttonTitle == '新增'">
                <px-scrollbar>
                  <div style="display: flex; width: 100%">
                    <div class="tableTop">
                      <div class="topList" style="background-color: #e7eefb">检测项目</div>
                      <div v-for="item in waterTestList" :key="item.key" class="topList">{{ item.key }}</div>
                    </div>
                    <div class="tableMain">
                      <div class="topList" style="background-color: #e7eefb">单位</div>
                      <div v-for="item in waterTestList" :key="item.key" class="topList">
                        <span v-if="activeName === 'fixed'"> {{ item.itemUnit }}</span>
                        <px-input v-else v-model="item.itemUnit" style="width: 100%; height: 23px" />
                      </div>
                    </div>
                    <div class="tableMain">
                      <div class="topList" style="background-color: #e7eefb">Control limit</div>
                      <div v-for="item in waterTestList" :key="item.key" class="topList">
                        <span v-if="activeName === 'fixed'">{{ item.controlValue }}</span>
                        <px-input v-else v-model="item.controlValue" style="width: 100%; height: 23px" />
                      </div>
                    </div>
                    <div class="tableMain">
                      <div class="topList" style="background-color: #e7eefb; border-right: 1px solid #dfdfdf">检测结果</div>
                      <div
                        v-for="item in equipdata.testResult"
                        :key="item.key"
                        class="topList testResult"
                        style="padding: 3px; border-right: 1px solid #dfdfdf"
                      >
                        <px-icon v-if="item.arrow === 1" color="#EF4444">
                          <Top />
                        </px-icon>
                        <px-icon v-if="item.arrow === 2" color="#EF4444">
                          <Bottom />
                        </px-icon>
                        <px-input v-model="item.value" style="width: 100%; height: 23px" clearable @input="handleTestResult" />
                      </div>
                    </div>
                  </div>
                </px-scrollbar>
              </div>
              <div v-if="buttonTitle == '编辑'">
                <px-scrollbar>
                  <div style="display: flex">
                    <div class="tableTop">
                      <div class="topList" style="background-color: #e7eefb">检测项目</div>
                      <div v-for="item in equipdata.testItems" :key="item.key" class="topList">{{ item.key }}</div>
                    </div>
                    <div class="tableMain">
                      <div class="topList" style="background-color: #e7eefb">单位</div>
                      <div v-for="item in equipdata.testItems" :key="item.key" class="topList">
                        <span v-if="activeName === 'fixed'"> {{ item.itemUnit }}</span>
                        <px-input v-else v-model="item.itemUnit" style="width: 100%; height: 23px" />
                      </div>
                    </div>
                    <div class="tableMain">
                      <div class="topList" style="background-color: #e7eefb">Control limit</div>
                      <div v-for="item in equipdata.testItems" :key="item.key" class="topList">
                        <span v-if="activeName === 'fixed'">{{ item.controlValue }}</span>
                        <px-input v-else v-model="item.controlValue" style="width: 100%; height: 23px" />
                      </div>
                    </div>
                    <div class="tableMain">
                      <div class="topList" style="background-color: #e7eefb; border-right: 1px solid #dfdfdf">检测结果</div>
                      <div
                        v-for="item in equipdata.testResult"
                        :key="item.key"
                        class="topList testResult"
                        style="padding: 3px; border-right: 1px solid #dfdfdf"
                      >
                        <px-icon v-if="item.arrow === 1" color="#EF4444">
                          <Top />
                        </px-icon>
                        <px-icon v-if="item.arrow === 2" color="#EF4444">
                          <Bottom />
                        </px-icon>
                        <px-input v-model="item.value" style="width: 100%; height: 23px" clearable @input="handleTestResult" />
                      </div>
                    </div>
                  </div>
                </px-scrollbar>
              </div>
            </div>
          </px-scrollbar>
        </div>
        <div
          class="box-card2"
          :style="{
            height: jiqicanshuFlg == true ? '' : '42px'
          }"
        >
          <div class="card-header" @click="setjiqicanshuFlg()">
            <div class="card-title">取样照片</div>
            <div class="card-main">
              <px-icon v-if="!jiqicanshuFlg">
                <ArrowDown />
              </px-icon>
              <px-icon v-else>
                <ArrowUp />
              </px-icon>
            </div>
          </div>
          <px-scrollbar class="form-div">
            <div class="info-form-content">
              <PhotoUpload
                :key="'ptoto1'"
                photoType="add"
                :photoData="{ moduleName: 'GENERAL_CHEMICALS' }"
                :photoList="equipdata.samplingPhoto"
                @changePhotoList="changePhotoList1"
                @savePhotoStatus="savePhotoStatus1"
              />
            </div>
          </px-scrollbar>
        </div>
        <div
          class="box-card3"
          :style="{
            height: shebeitaizhangFlg == true ? '' : '42px'
          }"
        >
          <div class="card-header" @click="setshebeitaizhangFlg()">
            <div class="card-title">附件</div>
            <div class="card-main">
              <px-icon v-if="!shebeitaizhangFlg">
                <ArrowDown />
              </px-icon>
              <px-icon v-else>
                <ArrowUp />
              </px-icon>
            </div>
          </div>
          <px-scrollbar class="form-div">
            <div class="info-form-content">
              <FileUpload
                fileType="add"
                :fileData="{ moduleName: 'GENERAL_CHEMICALS' }"
                :fileList="equipdata.attachmentFile"
                @changeFileList="changeFileList"
                @saveFileStatus="saveFileStatus"
              />
            </div>
          </px-scrollbar>
        </div>
      </px-form>
    </px-scrollbar>
    <div v-if="equipopenDetail" v-loading="subLoading" class="px-dialog-footer">
      <px-button @click="equipopenDetailcancel">取消</px-button>
      <px-button v-if="fromdisable" type="primary" @click="equipopenDetailcancel">关闭</px-button>
      <px-button v-else type="primary" :disabled="photoStatusFlag || fileStatusFlag" @click="equipopenDetailsubmitForm(detailruleFormRef)"
        >保存</px-button
      >
    </div>
    <px-dialog v-model="progressVisible" draggable clickHideContent title="上传进度" width="30%" center align-center>
      <px-progress :percentage="Math.floor(progressPercent)" />
    </px-dialog>
  </div>
</template>

<script setup name="Dict" lang="ts">
import Doc from "@/assets/svg/file/doc.svg?component";
import Pdf from "@/assets/svg/file/pdf.svg?component";
import Ppt from "@/assets/svg/file/ppt.svg?component";
import Txt from "@/assets/svg/file/txt.svg?component";
import Xsl from "@/assets/svg/file/xsl.svg?component";
// import useDictStore from '@/store/modules/dict'
defineOptions({
  name: "SystemDataDict"
});
// import { router } from "@/router";
import { ArrowLeft } from "@px-ui/icons-vue";
import { useRoute } from "vue-router";
import { PxMessage, PxMessageBox } from "px-ui";
import { getCurrentInstance, ref, toRefs, reactive, onMounted, watch, computed } from "vue";
import { getToken } from "@/utils/auth";
import PhotoUpload from "@/components/Upload/PhotoUpload.vue";
import FileUpload from "@/components/Upload/FileUpload.vue";
import { queryChildByTypeCodeAndItemValue, liquidFileDelete } from "@/api/waterClass";
import { generalqueryListPage, generalqueryDetail, generalqueryadd, generalquerydeleted, generalqueryupdate } from "@/api/chemicals";
import {
  pwMetalImpurityqueryListPage,
  pwMetalImpuritygetTestItem,
  pwMetalImpurityadd,
  pwMetalImpurityqueryDetail,
  pwMetalImpurityupdate,
  pwMetalImpuritydelete,
  pwMetalImpurityimportData,
  testQualityqueryScadaDiff,
  userlistPage,
  postTestManufacturerList,
  queryRecheckList,
  updateRecheckNumber,
  getSelectSimplingLocationList
} from "@/api/waterQualityDetection";
import uploadFiles from "../uploadFiles/indexcs.vue";
import { log } from "mathjs";
import spcCharts from "../components/spcChart.vue";
import { waterSpcAnalysis } from "@/api/spc";

const activeName = ref("fixed");
const reviewDialogVisible = ref(false);
const reviewList = reactive([]);
const selectedRowId = ref("");
const isReviewResult = ref(false);
const reviewDateRange = ref([]);
let samplingLocationCode = ref();
let selectId = ref("");
// 切换tab
const handleTabChange = (tab, event) => {
  queryParams.value.pageNum = 1;
  queryParams.value.samplingLocationCode = "";
  getList();
  querySelectSimplingLocationList();
};

// 获取取样点下拉列表
const querySelectSimplingLocationList = () => {
  getSelectSimplingLocationList({
    samplingLocationType: activeName.value === "fixed" ? 1 : 2,
    dictItemValue: "SP0104",
    dictTypeCode: "WTTS"
  }).then((response: any) => {
    liquidList.value = response;
  });
};
// 点击操作列的复核按钮
const handleReview = row => {
  samplingLocationCode.value = liquidList.value.find(item => row.samplingLocation === item.itemName)?.itemValue;
  let samplingTimeFrom = row.samplingDate + " " + row.samplingTime + ":00";
  reviewDateRange.value.length = 0;
  reviewDateRange.value[0] = samplingTimeFrom;
  selectId.value = row.id;
  selectedRowId.value = "";
  reviewDialogVisible.value = true;
  if (row.recheckId) {
    getDetail(row.recheckId);
    isReviewResult.value = true;
  } else {
    getRecheckList({
      samplingTimeFrom
    });
  }
};
// 查询复检记录
const getRecheckList = async data => {
  const res = await queryRecheckList({
    samplingLocationCode: samplingLocationCode.value,
    samplingLocationType: 1,
    id: selectId.value,
    ...data
  });
  reviewList.length = 0;
  reviewList.push(...res);
};
// 查询详情
const getDetail = async id => {
  const data = await pwMetalImpurityqueryDetail({ id });
  reviewList.length = 0;
  reviewList.push(data);
};
// 改变取样日期
const changeReviewDateRange = _ => {
  let samplingTimeFrom = reviewDateRange.value[0];
  let samplingTimeTo = reviewDateRange.value[1];
  selectedRowId.value = "";
  getRecheckList({
    samplingTimeFrom,
    samplingTimeTo
  });
};
// 关联按钮
const associate = async () => {
  let recheckNumber = reviewList.find(item => item.id === selectedRowId.value).documentNumber;
  await updateRecheckNumber({
    id: selectId.value,
    recheckNumber
  });
  PxMessage({
    message: "关联成功",
    type: "success"
  });
  getDetail(selectedRowId.value);
  getList();
  isReviewResult.value = true;
};
// 重新关联按钮
const reAssocite = _ => {
  selectedRowId.value = "";
  isReviewResult.value = false;
  changeReviewDateRange();
};
// 取消按钮
const handleClose = (done: () => void) => {
  done();
};
const options = [
  {
    itemValue: "system1",
    itemName: "系统1"
  },
  {
    itemValue: "system2",
    itemName: "系统2"
  }
];
const fileList = ref([]);
// 批量导入
const batchImport = async options => {
  try {
    const formData = new FormData();
    formData.append("file", options.file);
    await pwMetalImpurityimportData(formData);
    PxMessage.success("批量导入成功");
    resetQuery();
  } catch (error) {
    console.log(error);
  }
};
const jibenxinxiFlg = ref(true);
const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 1), new Date(2000, 1, 1, 23, 59, 59)];
const setqingdanFlg = () => {
  jibenxinxiFlg.value = !jibenxinxiFlg.value;
};
const jiqicanshuFlg = ref(true);
const setjiqicanshuFlg = () => {
  jiqicanshuFlg.value = !jiqicanshuFlg.value;
};
const shebeitaizhangFlg = ref(true);
const setshebeitaizhangFlg = () => {
  shebeitaizhangFlg.value = !shebeitaizhangFlg.value;
};
const moxingshezhiFlg = ref(true);
const setmoxingshezhiFlg = () => {
  moxingshezhiFlg.value = !moxingshezhiFlg.value;
};
const setreceiveCompanyCode = val => {
  let setvalue = null;
  setvalue = liquidList.value.find(option => option.itemCode == val);
  if (setvalue && setvalue?.itemDesc != "") {
    queryParams.value.receiveCompanyCode = JSON.parse(setvalue.itemDesc).receiveCompanyCode;
  } else {
    queryParams.value.receiveCompanyCode = "";
  }
  //console.log(setvalue);
};

const changesamplingOperator = val => {
  userList.value.forEach(item => {
    if (item.value == val) {
      equipdata.value.samplingOperator = item.label;
    }
  });
};
const changeresponsiblePerson = val => {
  userList.value.forEach(item => {
    if (item.value == val) {
      equipdata.value.responsiblePerson = item.label;
    }
  });
};
const route = useRoute();
onMounted(() => {
  if (route.query.equipmentId) {
    handleDetail(route.query.equipmentId);
  }
  querySelectSimplingLocationList();
});
const { proxy }: any = getCurrentInstance();

const typeList = ref([]);
const detailruleFormRef = ref();
const progressVisible = ref(false);
const open = ref(false);
const equipopen = ref(false);
const dialogVisible = ref(false);
const equipopenDetail = ref(false);
const fromdisable = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const typeIdloading = ref(false);
const total = ref(0);
const progressPercent = ref(0);
const title = ref("");
const dateRange = ref([]);

// 图片是否上传完，是否可以保存
const savePhotoStatus1 = val => {
  photoStatusFlag.value = val;
};
const savePhotoStatus2 = val => {
  photoStatusFlag.value = val;
};
const savePhotoStatus3 = val => {
  photoStatusFlag.value = val;
};
const savePhotoStatus4 = val => {
  photoStatusFlag.value = val;
};
// 文件是否上传完，是否可以保存
const saveFileStatus = val => {
  fileStatusFlag.value = val;
};

const waterstatusList = [
  {
    value: "VALID",
    name: "全部"
  },
  {
    value: "INVALID",
    name: "已删除"
  }
];
const buttonTitle = ref("");
const data = reactive({
  liquidList: [],
  transportCompanyList: [],
  receiveCompanyList: [],
  typeIdList: [],
  categoryList: [],
  equipmentTypeList: [],
  positionList: [],
  equipmentDeptList: [],
  modelIdList: [],
  form: {},
  photoStatusFlag: false,
  fileStatusFlag: false,
  tableColumns: [],
  waterTestList: [],
  testManufacturerList: [],
  equipdata: {
    id: 0,
    documentNumber: "",
    samplingTime: "",
    drainageTimeFrom: "",
    drainageTimeTo: "",
    samplingLocationCode: "",
    drainageVolume: "",
    testManufacturer: "",
    samplingOperatorId: "",
    samplingOperator: "",
    responsiblePersonId: "",
    responsiblePerson: "",
    samplingPhoto: [],
    attachmentFile: [],
    testItems: [],
    useDateFrom: [],
    testResult: [],
    remarks: "",
    reportNumber: "",
    testConclusion: ""
  },
  queryParams: {
    orderByColumn: "",
    isAsc: "",
    samplingLocationCode: "",
    samplingTimeFrom: "",
    samplingTimeTo: "",
    orderBy: "",
    pageNum: 1,
    pageSize: 20,
    samplingLocationType: 1
  },
  rules: {
    samplingTime: [{ required: true, message: "取样时间不能为空", trigger: "change" }],
    useDateFrom: [{ required: true, message: "排水时段不能为空", trigger: "change" }],
    samplingLocationCode: [{ required: true, message: "取样点不能为空", trigger: "change" }],
    drainageVolume: [{ required: true, message: "排水量(m³)不能为空", trigger: "blur" }],
    testManufacturer: [{ required: true, message: "检测机构不能为空", trigger: "blur" }],
    samplingOperatorId: [{ required: true, message: "取样人不能为空", trigger: "blur" }],
    responsiblePersonId: [{ required: true, message: "负责人不能为空", trigger: "blur" }],
    reportNumber: [{ required: true, message: "认证报告编号不能为空", trigger: "blur" }]
  },
  headers: {
    Authorization: "Bearer " + getToken().accessToken || ""
  },
  moduleName: "",
  dialogImageUrl: "",
  imageVisible: false,
  userList: []
});

const {
  liquidList,
  transportCompanyList,
  receiveCompanyList,
  queryParams,
  tableColumns,
  form,
  rules,
  equipdata,
  waterTestList,
  equipmentTypeList,
  modelIdList,
  photoStatusFlag,
  fileStatusFlag,
  userList,
  testManufacturerList
} = toRefs(data);

// 监听检测结果箭头显示
watch(
  () => equipdata.value.testResult,
  () => {
    equipdata.value.testResult?.forEach(item => {
      if (item.value) {
        if (item.value > item.top) {
          item.arrow = 1;
        } else if (item.value < item.bottom) {
          item.arrow = 2;
        } else {
          item.arrow = 0;
        }
      }
    });
  }
);

// 检测结果箭头显示
const handleTestResult = () => {
  equipdata.value.testResult?.forEach(item => {
    if (item.value) {
      if (item.value > item.top) {
        item.arrow = 1;
      } else if (item.value < item.bottom) {
        item.arrow = 2;
      } else {
        item.arrow = 0;
      }
    }
  });
};

const handleRemove = file => {
  equipdata.value.attachment = equipdata.value.attachment.filter(item => item !== file);
  let parmas = {
    fileId: file.fileId ? file.fileId : file?.response?.data?.fileId,
    ledgerCode: equipdata.value.ledgerCode
  };
  liquidFileDelete(parmas).then((response: any) => {
    PxMessage({
      type: "success",
      message: "删除成功"
    });
  });
};

// const checkTime = () => {
//   gettestQualityqueryScadaDiff();
// };
// const checkdrain = () => {
//   gettestQualityqueryScadaDiff();
// };
const waterAllTestList = ref([]);
const checklocation = () => {
  if (buttonTitle.value === "编辑") return;
  waterTestList.value = waterAllTestList.value.filter(res => res.smapleLocation === (equipdata.value.samplingLocationCode || "RO_OUTLET"));
  equipdata.value.testResult = waterAllTestList.value
    .filter(res => res.smapleLocation === (equipdata.value.samplingLocationCode || "RO_OUTLET"))
    .map(item => {
      return {
        key: item.key,
        value: "",
        arrow: 0,
        top: Number(item.controlValue?.split("~")[1]),
        bottom: Number(item.controlValue?.split("~")[0])
      };
    });
  // gettestQualityqueryScadaDiff();
};

// const gettestQualityqueryScadaDiff = () => {
//   let parmas = {
//     startTime: equipdata.value.samplingTime.split(" ")[0] + " " + equipdata.value.useDateFrom[0],
//     endTime: equipdata.value.samplingTime.split(" ")[0] + " " + equipdata.value.useDateFrom[1],
//     outlet: equipdata.value.samplingLocationCode
//   };
//   if (equipdata.value.useDateFrom.length > 0 && equipdata.value.samplingTime != "" && equipdata.value.samplingLocationCode != "") {
//     testQualityqueryScadaDiff(parmas).then(res => {
//       equipdata.value.drainageVolume = res;
//     });
//   }
// };
const getqueryCategoryList = () => {
  userlistPage({ page: 1, pageSize: 9999, deptNameList: ["WATER"], status: 0 }).then((response: any) => {
    userList.value = response.data.map(item => ({ label: `${item.username}-${item.realName}`, value: item.userId }));
  });

  //运输单位
  queryChildByTypeCodeAndItemValue({
    value: "TU01",
    typeCode: "WTTS"
  }).then((response: any) => {
    transportCompanyList.value = response;
  });
  //接收单位
  queryChildByTypeCodeAndItemValue({
    value: "RU01",
    typeCode: "WTTS"
  }).then((response: any) => {
    receiveCompanyList.value = response;
  });
};
getqueryCategoryList();
function getList() {
  loading.value = true;
  if (dateRange.value != null) {
    queryParams.value.samplingTimeFrom = dateRange.value[0];
    queryParams.value.samplingTimeTo = dateRange.value[1];
  } else {
    queryParams.value.samplingTimeFrom = "";
    queryParams.value.samplingTimeTo = "";
  }
  queryParams.value.samplingLocationType = activeName.value === "fixed" ? 1 : 2;
  pwMetalImpurityqueryListPage(queryParams.value).then((response: any) => {
    typeList.value = response.data;
    if (response.total != 0) {
      tableColumns.value = typeList.value[0].testResult;
    }
    total.value = response.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  equipopen.value = false;
}
function equipopenDetailcancel() {
  equipopenDetail.value = false;
}
/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    dictionaryName: undefined,
    dictionaryType: undefined,
    status: "VALID",
    remarks: undefined
  };
  proxy.resetForm("dictRef");
}
/** 搜索按钮操作 */
function handleQuery(type) {
  if (type == "search") {
    queryParams.value.pageNum = 1;
  }
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    orderByColumn: "",
    isAsc: "",
    samplingLocationCode: "",
    samplingTimeFrom: "",
    samplingTimeTo: "",
    orderBy: ""
  };
  dateRange.value = [];
  handleQuery("reset");
}

/** 新增按钮操作 */
function handleAdd() {
  buttonTitle.value = "新增";
  jibenxinxiFlg.value = true;
  jiqicanshuFlg.value = true;
  shebeitaizhangFlg.value = true;
  moxingshezhiFlg.value = true;
  equipopenDetail.value = true;
  fromdisable.value = false;
  equipmentTypeList.value = [];
  modelIdList.value = [];
  testManufacturerList.value = [];
  equipdata.value = {
    id: null,
    documentNumber: "",
    samplingTime: "",
    drainageTimeFrom: "",
    drainageTimeTo: "",
    samplingLocationCode: "",
    drainageVolume: "",
    testManufacturer: "",
    samplingOperatorId: "",
    samplingOperator: "",
    responsiblePersonId: "",
    responsiblePerson: "",
    samplingPhoto: [],
    attachmentFile: [],
    testItems: [],
    useDateFrom: [],
    testResult: [],
    remarks: "",
    reportNumber: "",
    testConclusion: ""
  };
  pwMetalImpuritygetTestItem().then((response: any) => {
    waterAllTestList.value = response;
    waterTestList.value = response.filter(res => res.smapleLocation === (equipdata.value.samplingLocationCode || "RO_OUTLET"));
    equipdata.value.testResult = response
      .filter(res => res.smapleLocation === (equipdata.value.samplingLocationCode || "RO_OUTLET"))
      .map(item => {
        return {
          key: item.key,
          value: "",
          arrow: 0,
          top: Number(item.controlValue?.split("~")[1]),
          bottom: Number(item.controlValue?.split("~")[0])
        };
      });
    console.log(equipdata.value.testResult, equipdata.value.samplingLocationCode);
  });
  postTestManufacturerList().then(res => {
    testManufacturerList.value.push(...res);
  });
}

const handleDetail = async val => {
  jibenxinxiFlg.value = true;
  jiqicanshuFlg.value = true;
  shebeitaizhangFlg.value = true;
  moxingshezhiFlg.value = true;
  testManufacturerList.value = [];
  const data = await pwMetalImpurityqueryDetail({ id: val });

  equipopen.value = true;
  // equipopenDetail.value = true;
  fromdisable.value = true;
  equipdata.value = data;
  equipdata.value.useDateFrom = [data?.drainageTimeFrom, data?.drainageTimeTo];
  if (data?.samplingPhoto && data?.samplingPhoto.length > 0) {
    data?.samplingPhoto.forEach(item => {
      item.url = item.fileUrl;
      item.name = item.originalName;
    });
    equipdata.value.samplingPhoto = data?.samplingPhoto;
  } else {
    equipdata.value.samplingPhoto = [];
  }
  if (data.attachmentFile && data.attachmentFile.length > 0) {
    data.attachmentFile.forEach(item => {
      item.url = item.fileUrl;
      item.name = item.originalName;
    });
    equipdata.value.attachmentFile = data.attachmentFile;
  } else {
    equipdata.value.attachmentFile = [];
  }
  if (activeName.value !== "fixed") {
    equipdata.value.samplingLocationCode = equipdata.value.samplingLocationName;
  }
  equipdata.value.testResult = data.testItems.map(item => {
    return {
      key: item.key,
      value: item.testValue,
      arrow: 0,
      top: item.controlValue?.split("~")[1],
      bottom: item.controlValue?.split("~")[0]
    };
  });
  spcCurrentKey.value = {
    key: "",
    uploadSpcJob: "",
    onlineSpcJob: ""
  };
  postTestManufacturerList().then(res => {
    testManufacturerList.value.push(...res);
  });
};

const handleEditor = async val => {
  buttonTitle.value = "编辑";
  jibenxinxiFlg.value = true;
  jiqicanshuFlg.value = true;
  shebeitaizhangFlg.value = true;
  moxingshezhiFlg.value = true;
  testManufacturerList.value = [];
  const data = await pwMetalImpurityqueryDetail({ id: val });
  equipopenDetail.value = true;
  fromdisable.value = false;
  equipdata.value = data;
  equipdata.value.samplingOperatorId = data.samplingOperatorId != "" ? Number(data.samplingOperatorId) : "";
  equipdata.value.responsiblePersonId = data.responsiblePersonId != "" ? Number(data.responsiblePersonId) : "";
  equipdata.value.useDateFrom = [data?.drainageTimeFrom, data?.drainageTimeTo];
  if (data?.samplingPhoto && data?.samplingPhoto.length > 0) {
    data?.samplingPhoto.forEach(item => {
      item.url = item.fileUrl;
      item.name = item.originalName;
    });
    equipdata.value.samplingPhoto = data?.samplingPhoto;
  } else {
    equipdata.value.samplingPhoto = [];
  }
  if (data.attachmentFile && data.attachmentFile.length > 0) {
    data.attachmentFile.forEach(item => {
      item.url = item.fileUrl;
      item.name = item.originalName;
    });
    equipdata.value.attachmentFile = data.attachmentFile;
  } else {
    equipdata.value.attachmentFile = [];
  }
  if (activeName.value !== "fixed") {
    equipdata.value.samplingLocationCode = equipdata.value.samplingLocationName;
  }
  equipdata.value.testResult = data.testItems.map(item => {
    return {
      key: item.key,
      value: item.testValue,
      arrow: 0,
      top: Number(item.controlValue?.split("~")[1]),
      bottom: Number(item.controlValue?.split("~")[0])
    };
  });
  postTestManufacturerList().then(res => {
    testManufacturerList.value.push(...res);
  });
};
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
// 新的图片列表
const changePhotoList1 = val => {
  equipdata.value.samplingPhoto = val;
};

// 新的文件列表
const changeFileList = val => {
  equipdata.value.attachmentFile = val;
};
/** 提交按钮 */
const subLoading = ref(false);
const equipopenDetailsubmitForm = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      subLoading.value = true;
      let testResult = {};
      if (activeName.value === "fixed") {
        equipdata.value.testResult?.forEach(item => {
          testResult[item.key] = item.value;
        });
      } else {
        equipdata.value.testResult?.forEach(item => {
          testResult[item.key] = {
            currentValue: item.value
          };
        });
        if (buttonTitle.value == "新增") {
          waterTestList.value.forEach(item => {
            Object.assign(testResult[item.key], {
              minValue: item.controlValue?.split("~")[0],
              maxValue: item.controlValue?.split("~")[1],
              testItemUnit: item.itemUnit
            });
          });
        } else {
          equipdata.value.testItems.forEach(item => {
            Object.assign(testResult[item.key], {
              minValue: item.controlValue?.split("~")[0],
              maxValue: item.controlValue?.split("~")[1],
              testItemUnit: item.itemUnit
            });
          });
        }
        console.log(testResult, 777777777);
        for (const key in testResult) {
          testResult[key] = JSON.stringify(testResult[key]);
        }
        console.log(testResult, 777777777);
      }
      const params = {
        id: equipdata.value.id,
        documentNumber: equipdata.value.documentNumber,
        samplingTime: equipdata.value.samplingTime,
        drainageTimeFrom: equipdata.value.useDateFrom[0],
        drainageTimeTo: equipdata.value.useDateFrom[1],
        samplingLocationCode: equipdata.value.samplingLocationCode,
        drainageVolume: equipdata.value.drainageVolume,
        testManufacturer: equipdata.value.testManufacturer,
        samplingOperatorId: equipdata.value.samplingOperatorId,
        responsiblePersonId: equipdata.value.responsiblePersonId,
        samplingOperator: equipdata.value.samplingOperator,
        responsiblePerson: equipdata.value.responsiblePerson,
        samplingPhoto: equipdata.value.samplingPhoto,
        attachmentFile: equipdata.value.attachmentFile,
        testResult: testResult,
        updateTime: equipdata.value.updateTime,
        remarks: equipdata.value.remarks,
        reportNumber: equipdata.value.reportNumber,
        testConclusion: equipdata.value.testConclusion,
        samplingLocationType: activeName.value === "fixed" ? 1 : 2
      };
      if (buttonTitle.value == "新增") {
        if (params.samplingPhoto.length > 0) {
          params.samplingPhoto = params.samplingPhoto.map(item => (item?.response?.data ? item?.response?.data.id : item.id));
        }
        if (params.attachmentFile.length > 0) {
          params.attachmentFile = params.attachmentFile.map(item => (item?.response?.data ? item?.response?.data.id : item.id));
        }
        pwMetalImpurityadd(params)
          .then((response: any) => {
            PxMessage({
              message: `${buttonTitle.value == "新增" ? "添加成功" : "修改成功"}`,
              type: "success"
            });
            resetQuery();
            querySelectSimplingLocationList();
            subLoading.value = false;
            equipopenDetail.value = false;
          })
          .catch(() => {
            subLoading.value = false;
          });
      } else {
        if (params.samplingPhoto.length > 0) {
          params.samplingPhoto = params.samplingPhoto.map(item => (item?.response?.data ? item?.response?.data.id : item.id));
        }
        if (params.attachmentFile.length > 0) {
          params.attachmentFile = params.attachmentFile.map(item => (item?.response?.data ? item?.response?.data.id : item.id));
        }
        pwMetalImpurityupdate(params)
          .then((response: any) => {
            PxMessage({
              message: `${buttonTitle.value == "新增" ? "添加成功" : "修改成功"}`,
              type: "success"
            });
            resetQuery();
            querySelectSimplingLocationList();
            subLoading.value = false;
            equipopenDetail.value = false;
          })
          .catch(() => {
            subLoading.value = false;
          });
      }
    }
  });
};
/** 删除按钮操作 */
function handleDelete(row) {
  //console.log(row);
  // const dictIds = [];
  // if (row.equipmentId != undefined) {
  //   dictIds.push(row.equipmentId);
  // } else {
  //   dictIds.push(...ids.value);
  // }
  PxMessageBox.confirm("是否确认删除？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const data = await pwMetalImpuritydelete({ id: row.id });
      PxMessage({
        message: "删除成功",
        type: "success"
      });
      getList();
    })
    .catch(() => {});
}

/** 导出按钮操作 */
const { VITE_FANRUAN_BASE_URL, VITE_SERVE_API_STATIC_URL } = import.meta.env;
const handleImport = () => {
  dialogVisible.value = true;
};

const submitHandler = async res => {
  for (const key in res) {
    let e = equipdata.value.testResult.find(item => item.key === key);
    e.value = res[key];
  }
  const message = "上传成功";
  PxMessage.success(message);
  handleTestResult();
  moxingshezhiFlg.value = true;
  // await getList();
};
function downloadFile(url, fileName) {
  const link = document.createElement("a");
  link.href = url;
  link.download = fileName || "downloaded-file"; // 备用文件名
  link.style.display = "none";

  // 兼容性处理
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);

  // 释放内存（针对Blob URL）
  if (url.startsWith("blob:")) {
    URL.revokeObjectURL(url);
  }
}
function handleExport() {
  if (dateRange.value != null && dateRange.value.length > 0 && queryParams.value.samplingLocationCode != "") {
    let Token = getToken().accessToken || "";
    // proxy.download("post", "/operation/api/v1/water/testQuality/pwMetalImpurity/export", queryParams.value, "水质检测-纯水金属阴阳离子.xlsx");
    let type = activeName.value === "fixed" ? 1 : 2;
    let fileName = activeName.value === "fixed" ? "纯水水质检测报表-固定取样" : "纯水水质检测报表-非固定取样";
    let url = `${VITE_FANRUAN_BASE_URL}/webroot/decision/view/report?viewlet=water%252F%25E7%25BA%25AF%25E6%25B0%25B4%25E6%25B0%25B4%25E8%25B4%25A8%25E6%25A3%2580%25E6%25B5%258B%25E6%258A%25A5%25E8%25A1%25A8.cpt&token=${Token}&from=${dateRange.value[0]}&to=${dateRange.value[1]}&location=${queryParams.value.samplingLocationCode}&format=excel&extype=simple&facCode=${localStorage.getItem("facCode") || ""}&apiHost=${VITE_SERVE_API_STATIC_URL}&type=${type}&__filename__=${fileName}`;
    downloadFile(url);
  } else {
    PxMessage({
      message: "请选择时间和取样点后再导出",
      type: "error"
    });
  }
}

// SPC分析
const spcCurrentKey = ref({
  key: "",
  uploadSpcJob: "",
  onlineSpcJob: ""
});
const selectSpcHandler = params => {
  waterSpcAnalysis({
    smapleLocation: equipdata.value.samplingLocationCode,
    testItem: params.key
  }).then(res => {
    spcCurrentKey.value = {
      key: params.key,
      uploadSpcJob: res?.uploadSpcJob || "",
      onlineSpcJob: res?.onlineSpcJob || ""
    };
  });
};

getList();
</script>
<style scoped lang="scss">
.testResult {
  display: flex;
  align-items: center;
}

.addEquip {
  position: absolute;
  top: 0;
  top: 5px;
  left: 0;
  width: calc(100% - 48px);
  height: calc(100% - 40px);
  margin: 24px;
  background: white;
}

.editorEquip {
  position: absolute;
  top: 0;
  top: 5px;
  left: 0;
  width: calc(100% - 48px);
  height: calc(100% - 40px);
  margin: 24px;
  background: white;
}

.px-dialog-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 2002;
  width: 100%;
  height: 50px;
  padding-top: 10px;
  padding-right: 34px;
  text-align: right;
  background: white;
  box-shadow: 0 0 10px 0 rgb(0 0 0 / 16%);
}

.card-header {
  min-height: 40px;
  padding: 14px 15px 7px !important;
  cursor: pointer;
  user-select: none;
  background: #e7eefb;
}

.card-title {
  float: left;
  line-height: 14px;
}

.card-main {
  float: left;
  margin: -3px 8px 0 5px;
  cursor: pointer;
}

.box-card1 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card2 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card3 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card4 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.demo-form-inline {
  .px-input {
    --px-input-width: calc(100% - 100px);
  }

  .px-form-item {
    width: 100%;
  }

  .px-textarea__inner {
    width: calc(100% - 100px) !important;
  }

  .px-form-item__label {
    font-weight: 400 !important;
  }
}

.form-div {
  padding: 24px;

  .px-row {
    margin-bottom: 16px;
  }
}

.px-icon {
  font-size: 16px !important;
}

:deep(.px-tabs__header) {
  // padding-left: 6px !important;
}

:deep(.px-tabs--top .px-tabs__item.is-top.is-active) {
  border: none;

  .pane-bottom {
    line-height: 30px;
    border-bottom: 2px solid #3b82f6;
  }
}

:deep(.px-tabs .px-tabs__item) {
  .pane-bottom {
    line-height: 30px;
  }
}

.pane-line {
  position: absolute;
  top: 12px;
  right: 0;
  height: 15px;
  color: #dcdcdc;
  border-left: 1px solid #dcdcdc;
}

:deep(.custom-form-ui .px-form-item) {
  width: 250px !important;
}

.filename {
  position: absolute;
  bottom: -30px;
  width: 96px;
  overflow: hidden;
  color: rgb(166 167 172);
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.px-descriptions__label.px-descriptions__cell.is-bordered-label) {
  width: 166px;
  background: #e7eefb;
  border: 1px solid #dfdfdf;
}

:deep(.px-descriptions__body .px-descriptions__table.is-bordered .px-descriptions__cell) {
  border: 1px solid #dfdfdf;
}

.cell-item {
  text-align: right;
}

:deep(.px-table__header) {
  thead {
    tr {
      background-color: #e7eefb !important;

      th {
        font-size: 14px;
        font-weight: bold;
        color: #000;
        background-color: #e7eefb !important;
      }
    }
  }
}

:deep(.px-table--isfixedHeader .px-table__header-wrapper .px-table-fixed-column--right) {
  background-color: #e7eefb !important;
}

.center2 {
  :deep(.px-descriptions__body) {
    table {
      border-left: none;

      .is-bordered-label {
        border-left: none !important;
      }

      // .is-bordered-content {
      //   border-right: none !important;
      // }
    }
  }
}

.center3 {
  :deep(.px-descriptions__body) {
    table {
      border-top: none;

      .is-bordered-label {
        border-top: none !important;
      }

      .is-bordered-content {
        border-top: none !important;
      }
    }
  }
}

.center4 {
  :deep(.px-descriptions__body) {
    table {
      border-top: none;
      border-left: none;

      .is-bordered-label {
        border-top: none !important;
        border-left: none !important;
      }

      .is-bordered-content {
        border-top: none !important;
      }
    }
  }
}

.tableTop {
  // display: flex;
  // border-right: 1px solid #dfdfdf;
  flex: 1;

  .topList {
    flex: 1;
    // width: 125px;
    height: 36px;
    padding: 6px;
    font-size: 14px;
    font-weight: bold;
    line-height: 23px;
    color: #000;
    // background-color: #e7eefb !important;
    border: 1px solid #dfdfdf;
    border-right: none;
    border-bottom: none;

    &:nth-last-child(1) {
      border-bottom: 1px solid #dfdfdf;
    }
  }
}

.tableMain {
  // display: flex;
  // border-right: 1px solid #dfdfdf;
  flex: 1;

  .topList {
    flex: 1;
    // width: 125px;
    height: 36px;
    padding: 6px;
    font-size: 14px;
    line-height: 23px;
    color: #000;
    border: 1px solid #dfdfdf;
    border-right: none;
    border-bottom: none;

    &:nth-last-child(1) {
      border-bottom: 1px solid #dfdfdf;
    }
  }
}

.detailTableTop {
  display: flex;
  // border-right: 1px solid #dfdfdf;

  .detailTopList {
    flex: 1;
    min-width: 125px;
    padding: 6px;
    font-size: 14px;
    font-weight: bold;
    line-height: 23px;
    color: #000;
    background-color: #e7eefb !important;
    border: 1px solid #dfdfdf;
    border-right: none;

    &:nth-last-child(1) {
      border-right: 1px solid #dfdfdf;
    }
  }
}

.detailTableMain {
  display: flex;
  // border-right: 1px solid #dfdfdf;

  .detailTopList {
    flex: 1;
    min-width: 125px;
    padding: 6px;
    font-size: 14px;
    line-height: 23px;
    color: #000;
    border: 1px solid #dfdfdf;
    border-top: none;
    border-right: none;

    &:nth-last-child(1) {
      border-right: 1px solid #dfdfdf;
    }

    .detailSpc {
      width: 90px;
      height: 23px;
      margin: auto;
      line-height: 23px;
      color: #fff;
      text-align: center;
      cursor: pointer;
      background-color: #dcdcdc;
      border-radius: 5px;
    }
  }
}
</style>
